package com.book.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.nio.cs.ISO_8859_2;

import com.book.dao.DownloadFileDao;
import com.book.domain.DownloadFile;

/**
 * Servlet implementation class DownloadFileServlet
 */
public class DownloadFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadFileServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	 int id=  Integer.parseInt( request.getParameter("id"));
	 DownloadFileDao downloadFileDao=new DownloadFileDao();
	 DownloadFile downloadFile=new DownloadFile();
	 downloadFile.setId(id);
	 DownloadFile downloadFile2= downloadFileDao.selectDownloadFile(downloadFile);
	    response.setCharacterEncoding("utf-8");
         String filename1=downloadFile2.getFilerealname();
         String filename2=new String(filename1.getBytes("gbk"),"ISO-8859-1");
         response.setContentType( "application/x-octetstream;charset=gbk "); 
	    response.setHeader("Content-disposition",  "attachment;filename=" +filename2 );
		ServletOutputStream out = response.getOutputStream();
		BufferedInputStream bis = null;
	    BufferedOutputStream bos = null;
	    String pathname=null;
	    pathname=request.getRealPath("/")+"download/"+downloadFile2.getFilename();
		try {
		      bis = new BufferedInputStream(new FileInputStream(new File(pathname)));
		      bos = new BufferedOutputStream(out);
		      byte[] buff = new byte[2048];
		      int bytesRead;
		      while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
		        bos.write(buff, 0, bytesRead);
		      }
		    } catch (IOException e) {
		      throw e;
		    } finally {
		      if (bis != null)
		        bis.close();
		      if (bos != null)
		        bos.close();
		    }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                doGet(request, response);
	}

}
